<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { useUserManagementStore } from '@/stores/userManagement'
import { useRouter } from 'vue-router'
import { hasPermission, USER_PERMISSIONS } from '@/utils/permission'
import UserForm from './UserForm.vue'

const router = useRouter()
const userManagementStore = useUserManagementStore()

// 从 store 中获取响应式数据
const { userList, loading, pagination, searchForm, selectedUsers, mockRoles } = userManagementStore

// 表格选中行
const selectedRowKeys = ref([])

// 对话框状态
const showUserForm = ref(false)
const formMode = ref('create') // 'create' | 'edit'
const currentUser = ref(null)

// 表格列配置
const columns = [
  { colKey: 'row-select', type: 'multiple-select', width: 50 },
  { colKey: 'id', title: 'ID', width: 120 },
  { colKey: 'username', title: '用户名', width: 120 },
  { colKey: 'nickname', title: '昵称', width: 120 },
  { colKey: 'email', title: '邮箱', width: 200 },
  { colKey: 'phone', title: '手机号', width: 130 },
  { 
    colKey: 'status', 
    title: '状态',
    width: 100,
    cell: (h, { row }) => {
      return h('t-tag', {
        theme: row.status === 1 ? 'success' : 'danger',
        variant: 'light'
      }, row.status === 1 ? '正常' : '禁用')
    }
  },
  {
    colKey: 'roles',
    title: '角色',
    width: 150,
    cell: (h, { row }) => {
      return row.roles?.map(role => 
        h('t-tag', { 
          theme: 'primary', 
          variant: 'light',
          style: { marginRight: '4px' }
        }, role.name)
      )
    }
  },
  { 
    colKey: 'createdAt', 
    title: '创建时间',
    width: 180,
    cell: (h, { row }) => {
      return new Date(row.createdAt).toLocaleString()
    }
  },
  { colKey: 'operation', title: '操作', width: 200, fixed: 'right' }
]

// 计算属性
const hasSelected = computed(() => selectedRowKeys.value.length > 0)

// 权限检查
const canCreate = computed(() => hasPermission(USER_PERMISSIONS.CREATE))
const canEdit = computed(() => hasPermission(USER_PERMISSIONS.EDIT))
const canDelete = computed(() => hasPermission(USER_PERMISSIONS.DELETE))
const canBatchDelete = computed(() => hasPermission(USER_PERMISSIONS.BATCH_DELETE))
const canResetPassword = computed(() => hasPermission(USER_PERMISSIONS.RESET_PASSWORD))
const canToggleStatus = computed(() => hasPermission(USER_PERMISSIONS.TOGGLE_STATUS))

// 获取用户列表
const fetchUserList = async () => {
  const result = await userManagementStore.fetchUserList()
  if (!result.success) {
    MessagePlugin.error(result.message)
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  fetchUserList()
}

// 重置
const handleReset = () => {
  userManagementStore.resetSearchForm()
  handleSearch()
}

// 分页变化
const handlePageChange = (pageInfo) => {
  pagination.current = pageInfo.current
  pagination.pageSize = pageInfo.pageSize
  fetchUserList()
}

// 表格选择变化
const handleSelectChange = (value, { selectedRowData }) => {
  selectedRowKeys.value = value
  selectedUsers.value = selectedRowData
}

// 新增用户
const handleCreate = () => {
  formMode.value = 'create'
  currentUser.value = null
  showUserForm.value = true
}

// 编辑用户
const handleEdit = async (row) => {
  const result = await userManagementStore.getUserDetail(row.id)
  if (result.success) {
    formMode.value = 'edit'
    currentUser.value = result.data
    showUserForm.value = true
  } else {
    MessagePlugin.error(result.message)
  }
}

// 删除用户
const handleDelete = (row) => {
  const dialog = DialogPlugin.confirm({
    header: '确认删除',
    body: `确定要删除用户 "${row.nickname || row.username}" 吗？此操作不可恢复。`,
    confirmBtn: '确定删除',
    cancelBtn: '取消',
    theme: 'danger',
    onConfirm: async () => {
      const result = await userManagementStore.deleteUser(row.id)
      if (result.success) {
        MessagePlugin.success(result.message)
        fetchUserList()
      } else {
        MessagePlugin.error(result.message)
      }
      dialog.destroy()
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!hasSelected.value) {
    MessagePlugin.warning('请先选择要删除的用户')
    return
  }

  const dialog = DialogPlugin.confirm({
    header: '批量删除确认',
    body: `确定要删除选中的 ${selectedRowKeys.value.length} 个用户吗？此操作不可恢复。`,
    confirmBtn: '确定删除',
    cancelBtn: '取消',
    theme: 'danger',
    onConfirm: async () => {
      const result = await userManagementStore.batchDeleteUsers(selectedRowKeys.value)
      if (result.success) {
        MessagePlugin.success(result.message)
        selectedRowKeys.value = []
        fetchUserList()
      } else {
        MessagePlugin.error(result.message)
      }
      dialog.destroy()
    }
  })
}

// 切换用户状态
const handleToggleStatus = async (row) => {
  const newStatus = row.status === 1 ? 0 : 1
  const statusText = newStatus === 1 ? '启用' : '禁用'
  
  const dialog = DialogPlugin.confirm({
    header: '确认操作',
    body: `确定要${statusText}用户 "${row.nickname || row.username}" 吗？`,
    confirmBtn: `确定${statusText}`,
    cancelBtn: '取消',
    onConfirm: async () => {
      const result = await userManagementStore.updateUserStatus(row.id, newStatus)
      if (result.success) {
        MessagePlugin.success(result.message)
        fetchUserList()
      } else {
        MessagePlugin.error(result.message)
      }
      dialog.destroy()
    }
  })
}

// 重置密码
const handleResetPassword = (row) => {
  const dialog = DialogPlugin.confirm({
    header: '重置密码',
    body: `确定要重置用户 "${row.nickname || row.username}" 的密码吗？`,
    confirmBtn: '确定重置',
    cancelBtn: '取消',
    onConfirm: async () => {
      const result = await userManagementStore.resetUserPassword(row.id)
      if (result.success) {
        MessagePlugin.success(`密码重置成功，新密码：${result.data.newPassword}`)
      } else {
        MessagePlugin.error(result.message)
      }
      dialog.destroy()
    }
  })
}

// 查看用户详情
const handleViewDetail = (row) => {
  router.push(`/users/${row.id}`)
}

onMounted(() => {
  fetchUserList()
})
</script>

<template>
  <div class="user-list-container">
    <!-- 搜索区域 -->
    <t-card class="search-card">
      <t-form :data="searchForm" layout="inline">
        <t-form-item label="用户名">
          <t-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </t-form-item>
        <t-form-item label="昵称">
          <t-input v-model="searchForm.nickname" placeholder="请输入昵称" clearable />
        </t-form-item>
        <t-form-item label="邮箱">
          <t-input v-model="searchForm.email" placeholder="请输入邮箱" clearable />
        </t-form-item>
        <t-form-item label="手机号">
          <t-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </t-form-item>
        <t-form-item label="状态">
          <t-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <t-option :value="1" label="正常" />
            <t-option :value="0" label="禁用" />
          </t-select>
        </t-form-item>
        <t-form-item label="角色">
          <t-select v-model="searchForm.roleId" placeholder="请选择角色" clearable>
            <t-option 
              v-for="role in mockRoles" 
              :key="role.id" 
              :value="role.id" 
              :label="role.name" 
            />
          </t-select>
        </t-form-item>
        <t-form-item>
          <t-space>
            <t-button theme="primary" @click="handleSearch">
              <template #icon><t-icon name="search" /></template>
              查询
            </t-button>
            <t-button theme="default" @click="handleReset">
              <template #icon><t-icon name="refresh" /></template>
              重置
            </t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-card>

    <!-- 操作区域 -->
    <t-card class="table-card">
      <div class="table-header">
        <div class="table-title">
          <h3>用户列表</h3>
          <t-tag theme="primary" variant="light">共 {{ pagination.total }} 条记录</t-tag>
        </div>
        <t-space>
          <t-button 
            v-if="canBatchDelete"
            theme="danger" 
            variant="outline" 
            :disabled="!hasSelected"
            @click="handleBatchDelete"
          >
            <template #icon><t-icon name="delete" /></template>
            批量删除 ({{ selectedRowKeys.length }})
          </t-button>
          <t-button v-if="canCreate" theme="primary" @click="handleCreate">
            <template #icon><t-icon name="add" /></template>
            新增用户
          </t-button>
        </t-space>
      </div>

      <!-- 表格 -->
      <t-table
        :data="userList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        :selected-row-keys="selectedRowKeys"
        @page-change="handlePageChange"
        @select-change="handleSelectChange"
        stripe
        hover
        row-key="id"
      >
        <template #operation="{ row }">
          <t-space>
            <t-link theme="primary" hover="color" @click="handleViewDetail(row)">
              <t-icon name="view" /> 详情
            </t-link>
            <t-link v-if="canEdit" theme="primary" hover="color" @click="handleEdit(row)">
              <t-icon name="edit" /> 编辑
            </t-link>
            <t-dropdown v-if="canToggleStatus || canResetPassword || canDelete">
              <t-link theme="default" hover="color">
                <t-icon name="more" /> 更多
              </t-link>
              <t-dropdown-menu>
                <t-dropdown-item v-if="canToggleStatus" @click="handleToggleStatus(row)">
                  <t-icon :name="row.status === 1 ? 'poweroff' : 'check-circle'" />
                  {{ row.status === 1 ? '禁用' : '启用' }}
                </t-dropdown-item>
                <t-dropdown-item v-if="canResetPassword" @click="handleResetPassword(row)">
                  <t-icon name="lock-on" />
                  重置密码
                </t-dropdown-item>
                <t-dropdown-item v-if="canDelete" theme="danger" @click="handleDelete(row)">
                  <t-icon name="delete" />
                  删除
                </t-dropdown-item>
              </t-dropdown-menu>
            </t-dropdown>
          </t-space>
        </template>
      </t-table>
    </t-card>

    <!-- 用户表单对话框 -->
    <UserForm 
      v-model:visible="showUserForm"
      :mode="formMode"
      :user-data="currentUser"
      @success="fetchUserList"
    />
  </div>
</template>

<style scoped>
.user-list-container {
  height: 100%;
}

.search-card {
  margin-bottom: 16px;
}

.table-card {
  height: calc(100% - 100px);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h3 {
  margin: 0;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title h3 {
  margin: 0;
}
</style> 